import request from "@/utils/request";

// 上传文件
export const uploadFile = (
  file: File,
  onProgress?: (percentage: number) => void
) => {
  const formData = new FormData();
  formData.append("file", file);

  return request({
    url: "/uploads/aliyun",
    method: "post",
    data: formData,
    headers: {
      "Content-Type": "multipart/form-data",
    },
    onUploadProgress: (progressEvent) => {
      if (progressEvent.total && onProgress) {
        const percentage = Math.round(
          (progressEvent.loaded * 100) / progressEvent.total
        );
        onProgress(percentage);
      }
    },
  });
};

// 文件类型和大小验证
export const validateFile = (
  file: File,
  allowedTypes: string[] = ["image/jpeg", "image/png", "image/gif"],
  maxSize: number = 5
) => {
  // 验证文件类型
  if (!allowedTypes.includes(file.type)) {
    throw new Error("不支持的文件类型");
  }

  // 验证文件大小（MB）
  const fileSize = file.size / 1024 / 1024;
  if (fileSize > maxSize) {
    throw new Error(`文件大小不能超过${maxSize}MB`);
  }

  return true;
};
